package com.yyfax.ph.common.scan.idcard.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.*;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.ph.R;
import com.yyfax.ph.common.imageselector.utils.FileUtils;
import com.yyfax.ph.common.scan.Utils.Tools;
import com.yyfax.ph.common.scan.idcard.CameraManager;
import com.yyfax.ph.common.scan.idcard.CaptureActivityHandler;
import com.yyfax.ph.common.scan.idcard.CaptureListener;
import com.yyfax.ph.common.scan.idcard.widget.ViewfinderView;
import com.yyfax.ph.common.utils.ToastUtils;
import exocr.exocrengine.DictManager;
import exocr.exocrengine.EXIDCardResult;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;

public class ScanIdCardActivity extends Activity implements SurfaceHolder.Callback, View.OnClickListener, CaptureListener {
	public final static String IDINFO = "IDINFO";
	public final static String DIRECTION = "DIRECTION";
	public final static String BOTH_DIRECTION = "BOTH DIRECTION";
	public final static String SCAN_ID_RESULT = "scan_id_result";
	public final static String SCAN_ID_NAME_RESULT = "scan_id_name_result";
	public final static int MSG_GET_SCAN_ID_CARD = 0x12;
	private final static String TAG = ScanIdCardActivity.class.getSimpleName();
	private final static int SAVE_BITMAP = 0X01;

	private final MediaPlayer.OnCompletionListener playMusicListener = new MediaPlayer.OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};
	private final Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() {
		public void onShutter() {
			AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			mgr.playSoundEffect(AudioManager.FLAG_PLAY_SOUND);
		}
	};
	@BindView(R.id.idcard_scan_surface_view)
	SurfaceView mSurfaceView;
	@BindView(R.id.idcard_scan_finderview)
	ViewfinderView mFindView;//身份证正反面提示
	@BindView(R.id.idcard_scan_hint_iv)
	ImageView mIdCardScanHintIv;

	public static final String ID_FRONT_IMG_HEADER = "id_header_img_"; // 头像
	public static final String ID_FRONT_IMG_FILE_NAME = "id_front_img_"; // 正面
	public static final String ID_BACK_IMG_FILE_NAME = "id_back_img_"; // 反面
	private static final String ID_CARD_IMG_SAVE_DIR = FileUtils.ID_CARD_IMAGE_SAVE_PATH;

	boolean flashFlag = false;
	private MediaPlayer mediaPlayer;
	private boolean playMusicFlag = true;
	private CaptureActivityHandler handler;
	private boolean bCamera = true;
	private boolean hasSurface;
	private boolean bothDirection = false;
	private IdCardInfo idCardInfo;
	private ImageHandler imageHandler = new ImageHandler(this);
	private Bitmap mFrontBitMap;
	private Bitmap mHeaderBitMap;

	public static void startForResult(Activity activity, Intent intent, int requestCode) {

		activity.startActivityForResult(intent, requestCode);
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CameraManager.init(getApplication());
		setContentView(R.layout.capture_activity_layout);
		ButterKnife.bind(this);
		if (Build.VERSION.SDK_INT >= 19) {
			getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		check();
		initData();
		initView();
		initTipMusic();

	}

	/**
	 * 获取是拍身份证正面还是反面的标志  默认是正面 frontFlag
	 */
	private void initData() {
		if (null != getIntent()) {
			if (getIntent().hasExtra(BOTH_DIRECTION)) {
				bothDirection = getIntent().getBooleanExtra(BOTH_DIRECTION, false);
				idCardInfo = new IdCardInfo();
			}
		}
	}

	private void initView() {
		if (bothDirection) {
			ToastUtils.showToast(this, R.string.please_scan_id_front);
			mIdCardScanHintIv.setImageResource(R.drawable.id_forground_img);
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	/**
	 * 检查相机
	 */
	private void checkCamera() {
		bCamera = Tools.hardwareSupportCheck();
		if (!bCamera) {
			Toast.makeText(this, R.string.camera_error_msg, Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	/**
	 * 检查是否初始化扫描所必须的核心文件（字典）和授权
	 */
	private void check() {
		DictManager.getInstance().initDict(this, null);
		if (!DictManager.getInstance().hasInit()) {
			Toast.makeText(this, R.string.init_dict_failure_tip_of_expired_strs, Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		CLog.i(TAG, "onResume");
		checkCamera();
		SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
			CLog.i(TAG, " initCamera(surfaceHolder)");
		} else {
			surfaceHolder.addCallback(this);
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
				surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
			}
			CLog.i(TAG, "  surfaceHolder.addCallback(this);");
		}
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			Toast.makeText(this, "摄像头获取失败", Toast.LENGTH_SHORT).show();
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		if (null != mediaPlayer) {
			mediaPlayer.release();
			mediaPlayer = null;
		}
		DictManager.getInstance().finishDict();
		super.onDestroy();
	}

	@Override
	public void surfaceCreated(SurfaceHolder surfaceHolder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(surfaceHolder);
			CLog.i(TAG, "   initCamera(surfaceHolder);");
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
		hasSurface = false;
	}

	/**
	 * 切换开启灯光
	 */
	private void switchFlashLight() {
		if (flashFlag) {
			CameraManager.get().disableFlashlight();
		} else {
			CameraManager.get().enableFlashlight();
		}
		flashFlag = !flashFlag;
	}

	/**
	 * 识别成功播放提示音乐并且振动
	 */
	private void playMusicAndVibrate() {
		if (playMusicFlag && mediaPlayer != null) {
			// mediaPlayer.start();
		}
		Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		vibrator.vibrate(200);
	}

	/**
	 * 初始化提示音
	 */
	private void initTipMusic() {
		if (playMusicFlag && mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(playMusicListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	@Override
	public Handler getHandler() {
		CLog.i(TAG, "getHandler");
		return handler;
	}

	@Override
	public void getIdCardInfoSuccess(EXIDCardResult result) {
		if (null != result) {
			if (result.type == 1) {
				CLog.i(TAG, "检测到身份证正面：");
				CLog.i(TAG, "身份证号码：" + result.cardnum + "姓名：" + result.name + "性别：" + result.sex + "名族：：" + result.nation + "出生日期" + result.birth + "地址" + result.address);
				if (bothDirection) {
					if (null != idCardInfo) {
						if (TextUtils.isEmpty(idCardInfo.getName())
								&& TextUtils.isEmpty(idCardInfo.getAddress())
								&& TextUtils.isEmpty(idCardInfo.getIdNumber())
								&& TextUtils.isEmpty(idCardInfo.getNationality())
								&& TextUtils.isEmpty(idCardInfo.getSex())) {
							playMusicAndVibrate();
							mFrontBitMap = result.getIdCardBitmap();
							mHeaderBitMap = result.GetFaceBitmap();

							idCardInfo.setName(result.name);
							idCardInfo.setIdNumber(result.cardnum);
							idCardInfo.setNationality(result.nation);
							idCardInfo.setAddress(result.address);
							idCardInfo.setSex(result.sex);

						}
					}
					ToastUtils.showToast(this, R.string.please_scan_id_back, Toast.LENGTH_SHORT);
					mIdCardScanHintIv.setImageResource(R.drawable.id_background_img);
					if (null != handler) {
						handler.restartAutoFocus();
					}
					return;
				}
				playMusicAndVibrate();
				Intent data = new Intent();
				data.putExtra(SCAN_ID_RESULT, result.cardnum);
				data.putExtra(SCAN_ID_NAME_RESULT, result.name);
				setResult(RESULT_OK, data);
				finish();
			} else if (result.type == 2) {
				CLog.i(TAG, "检测到身份证反面");
				CLog.i(TAG, "签发机关" + result.office + "有效期限：" + result.validdate);
				if (bothDirection) {
					if (TextUtils.isEmpty(idCardInfo.getName())
							&& TextUtils.isEmpty(idCardInfo.getAddress())
							&& TextUtils.isEmpty(idCardInfo.getIdNumber())
							&& TextUtils.isEmpty(idCardInfo.getNationality())
							&& TextUtils.isEmpty(idCardInfo.getSex())) {
						ToastUtils.showToast(this, R.string.please_scan_id_front, Toast.LENGTH_SHORT);
						mIdCardScanHintIv.setImageResource(R.drawable.id_forground_img);
						if (null != handler) {
							handler.restartAutoFocus();
						}
						return;
					}
					if (null != idCardInfo) {
						playMusicAndVibrate();
						idCardInfo.setAuthority(result.office);
						idCardInfo.setValidity(result.validdate);
						Bitmap backBitMap = result.getIdCardBitmap();

						String idFrontImageHeaderFileName = ID_FRONT_IMG_HEADER + idCardInfo.getIdNumber() + ".jpg";
						String idFrontImageFileName = ID_FRONT_IMG_FILE_NAME + idCardInfo.getIdNumber() + ".jpg";
						String idBackImageFileName = ID_BACK_IMG_FILE_NAME + idCardInfo.getIdNumber() + ".jpg";

						if (null != backBitMap && null != mFrontBitMap) {
							boolean saveHeaderSuccess = FileUtils.saveBitmapToFile(ID_CARD_IMG_SAVE_DIR, idFrontImageHeaderFileName, mHeaderBitMap);
							boolean saveFrontSuccess = FileUtils.saveBitmapToFile(ID_CARD_IMG_SAVE_DIR, idFrontImageFileName, mFrontBitMap);
							boolean saveBackSuccess = FileUtils.saveBitmapToFile(ID_CARD_IMG_SAVE_DIR, idBackImageFileName, backBitMap);
							if (saveHeaderSuccess && saveBackSuccess && saveFrontSuccess) {
								galleryAddPic(ID_CARD_IMG_SAVE_DIR + idFrontImageHeaderFileName);
								galleryAddPic(ID_CARD_IMG_SAVE_DIR + idFrontImageFileName);
								galleryAddPic(ID_CARD_IMG_SAVE_DIR + idBackImageFileName);
								if (null != idCardInfo) {
									idCardInfo.setIdFrontHeaderImgPath(ID_CARD_IMG_SAVE_DIR + idFrontImageHeaderFileName);
									idCardInfo.setIdFrontImgPath(ID_CARD_IMG_SAVE_DIR + idFrontImageFileName);
									idCardInfo.setIdBackImgPath(ID_CARD_IMG_SAVE_DIR + idBackImageFileName);
								}
							}
						}
						// 保存图片成功与否不是扫卡的必要条件, 如果图片没保存,则下一个页面可拍照上传.
						imageHandler.sendEmptyMessage(SAVE_BITMAP);
					}
				}
			}
		}

	}

	private void galleryAddPic(String picPath) {
		Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		File f = new File(picPath);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		sendBroadcast(mediaScanIntent);
	}

	private void returnScanResult(EXIDCardResult result) {
		if (null != result) {
			if (result.type == 1) {
				if (bothDirection) {
					if (null != idCardInfo) {
						idCardInfo.setName(result.name);
						idCardInfo.setIdNumber(result.cardnum);
						idCardInfo.setNationality(result.nation);
						idCardInfo.setAddress(result.address);
					}
				}
				CLog.i(TAG, "检测到身份证正面：");
				CLog.i(TAG, "身份证号码：" + result.cardnum + "姓名：" + result.name + "性别：" + result.sex + "名族：：" + result.nation + "出生日期" + result.birth + "地址" + result.address);
			} else if (result.type == 2) {
				if (bothDirection) {
					if (null != idCardInfo) {
						idCardInfo.setAuthority(result.office);
						idCardInfo.setValidity(result.validdate);
					}
				}
				CLog.i(TAG, "检测到身份证反面");
				CLog.i(TAG, "签发机关" + result.office + "有效期限：" + result.validdate);
			}
		}

	}

	@Override
	public void getIdCardInfoFailure() {
		CLog.i(TAG, "检测失败");
	}

	@Override
	public Camera.ShutterCallback getShutterCallback() {
		return shutterCallback;
	}
//
//	//保存获取到的图片
//	private void saveBitMap(final Bitmap bitmap) {
//		GlobalVariableConfig.getExecutorService().execute(new Runnable() {
//			@Override
//			public void run() {
//				File outFile = FileUtils.createTmpFile(ScanIdCardActivity.this, storageDir);
//				if (null != outFile && null != bitmap) {
//					idFrontImageFile = outFile.getAbsolutePath();
//					//身份证小头像不压缩
//					boolean flag = BitmapOptimizer.compress(bitmap, idFrontImageFile, 100);
//					if (flag) {
//						if (null != idCardInfo) {
//							idCardInfo.setFilePath(idFrontImageFile);
//						}
//						imageHandler.sendEmptyMessage(SAVE_BITMAP);
//					}
//				}
//			}
//		});
//	}

	@Override
	public String getAPPpackageName() {
		return getPackageName();
	}

	@OnClick(R.id.idcard_scan_back_tv)
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.idcard_scan_back_tv:
				finish();
				break;
		}
	}

	private void processIdCardInfo() {
		if (null != idCardInfo) {
			Intent data = new Intent();
			data.putExtra(IDINFO, idCardInfo);
			setResult(RESULT_OK, data);
			finish();
		}
	}

	private static class ImageHandler extends Handler {

		WeakReference<ScanIdCardActivity> mWeakReferenceActivity;

		ImageHandler(ScanIdCardActivity activity) {
			mWeakReferenceActivity = new WeakReference<>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case SAVE_BITMAP:
					if (null != mWeakReferenceActivity) {
						ScanIdCardActivity misActivity = mWeakReferenceActivity.get();
						misActivity.processIdCardInfo();
					}
					break;
			}
		}
	}
}
